//
//  M_LikeView.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/26.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_LikeView: UIView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    //定义一个闭包类型
    typealias selBlock = ([String : Any?]) -> Void
    //声明一个变量
    var selBtnBack: selBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callselBlock(block: @escaping selBlock) {
        selBtnBack = block
    }
    
    var colltionView : UICollectionView?
    //商品列表数据
    var productListArr = [[String:Any?]]()
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    init() {
        super.init(frame: .zero)
        getDataList(zoneCode: "105001", pageIndex: 1, pageSize: 10, callback: { (conut) in
        })
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getDataList(zoneCode: String, pageIndex: Int, pageSize: Int,callback:@escaping (Int)->()) {
//            MBProgressHUD.showOrIncrease()
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                        "zoneCode":zoneCode,
                                        "pageIndex":pageIndex,
                                        "pageSize":pageSize]
            API.request(url: .M_GetRecommendProductList, params: params) { (result) in
//                MBProgressHUD.hideOrDecrease()

                if result.success {
                    if let dl = result.data?.getDictionary("data") {
                        self.productListArr = []
                        for item in dl.getDictList("items") ?? [] {
                            self.productListArr.append(item)
                        }
                    }
                    callback(self.productListArr.count)
                    self.colltionView?.reloadData()
                }
                else {
                    callback(0)
                }
        }
    }
    
    func addCar(productNo: String) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "productNo":productNo]
        API.request(url: .M_AddCart, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "成功加入购物车")
                popup.show(vc: UIViewController.topMostController()!)
                
                let noT = NSNotification.Name(rawValue: CAR_CHANGE)
                let dic = ["key":"value"]
                NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
            }
            else {
                let popup = PopupBox(infoText: result.errMsg ?? "加入购物车失败")
                popup.show(vc: UIViewController.topMostController()!)
            }
        }
    }

    override func draw(_ rect: CGRect) {
//        self.backgroundColor = .red
        if colltionView == nil {
            setupUI()
        }
    }
    
    override func layoutSubviews() {
//        self.backgroundColor = .red
        if colltionView == nil {
            setupUI()
        }
    }
    
    func setupUI() {
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 5, left: 10, bottom: 0, right: 10)
        layout.minimumLineSpacing = 7
        layout.minimumInteritemSpacing = 7
        colltionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        //注册一个cell
        colltionView!.register(M_ProductColCell.self, forCellWithReuseIdentifier:"cell")
        //注册一个head
        colltionView!.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        colltionView?.backgroundColor = .xF2F2F2
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 173, height: 251)
        self.addSubview(colltionView!)
        colltionView?.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        colltionView?.isScrollEnabled = false
    }
    
    
    ///collectionView delegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dic = productListArr[indexPath.row]
        if selBtnBack != nil {
            selBtnBack!(dic)
        }
    }
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return productListArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! M_ProductColCell
        let dic = productListArr[indexPath.row]
        cell.celldata = dic
//        cell.subLab.isHidden = true
        cell.callAddBlock {
            self.addCar(productNo: dic.getString("productNo") ?? "")
        }
        return cell
    }
    
    //返回HeadView的宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
            return CGSize(width: collectionView.bounds.width, height: 52)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var v = UICollectionReusableView()
        if kind == UICollectionView.elementKindSectionHeader{
            v = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
            v.drawImage(named: "headlike_37") { (make) in
                make.center.equalToSuperview()
            }
        }
        return v
    }
}
